<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NDatePicker,
  NSelect,
  NSpace,
  NModal,
  type DataTableColumns
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { format } from 'date-fns'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    width: '5rem'
  },
  {
    title: '发放月份',
    key: 'issueMonth',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '部门',
    key: 'deptName',
    width: '15rem',
    align: useStore.isCenter
  },
  {
    title: '人员',
    key: 'userName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '下发状态',
    key: 'distributionStatus',
    width: '10rem',
    align: useStore.isCenter,
    render(e) {
      return e.distributionStatus == '1' ? '已下发' : '未下发'
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '预览'
        }
      )
    ]
  }
]

//筛选条件
const timeRange = ref()
timeRange.value = format(Date.now(), 'yyyy-MM')
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    queryTableData(true)
  }
})

//部门类型
const deptId = ref()
const partList: any = ref([])
const getPartName = async () => {
  const [error, res] = await sendRequest({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  partList.value = res.data
}
getPartName()

//删除
const modalVisible = ref(false)
const againDelete = async () => {
  const [error, res] = await sendRequest({
    module: 'workBench',
    api: 'payrollSendDelete',
    override: {
      data: dataListSelections.value
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  queryTableData()
}

const handleDelete = () => {
  modalVisible.value = true
}

//工资单导入
const handleImpport = () => {
  router.push({
    path: '/OA/Workbench/PayrollSendImport'
  })
}

//下发工资单通知
const chosenIdLength = ref()
const demanIdLength = ref()
const handleSend = async () => {
  if (demanIdLength.value) {
    if (demanIdLength.value < chosenIdLength.value) {
      message.warning('请全部勾选未下发状态数据！')
    } else {
      const [error, res] = await sendRequest({
        module: 'workBench',
        api: 'payrollSendNotice',
        override: {
          data: dataListSelections.value
        }
      })
      if (error) return message.error(error.message)
      message.success(res.data)
      queryTableData()
    }
  } else {
    message.warning('请全部勾选未下发状态数据！')
  }
}

//预览
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Workbench/PayrollSendDetail',
    query: val
  })
}

//多选框勾选
type DataListSelectionsItem = {
  id: string
}
const notIssuedId = ref()
const dataListSelections: any = ref<DataListSelectionsItem[]>([])
function selectionChangeHandle(val: any, info: any) {
  dataListSelections.value = val
  notIssuedId.value = []
  info.map((i: any) => {
    if (i.distributionStatus == '0') {
      notIssuedId.value.push(i.id)
    }
  })
  chosenIdLength.value = dataListSelections.value?.length
  demanIdLength.value = notIssuedId.value?.length
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  dataListSelections.value = []
  const [error, res] = await sendRequest({
    module: 'workBench',
    api: 'payrollSendList',
    override: {
      params: {
        issueMonth: timeRange.value,
        deptId: deptId.value,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  if (error) return message.error(error.message)
  const tmp: any = res.data
  tableData.value = tmp?.list
  paginationReactive.itemCount = tmp.totalCount
  tableLoading.value = false
}


const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/payrollSend') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="发放月份:">
            <NDatePicker input-readonly placeholder="请选择发放月份" type="month" v-model:formatted-value="timeRange"
              value-format="yyyy-MM" clearable style="width: 200px" />
          </NFormItem>
          <NFormItem label="部门:">
            <NSelect :options="partList" v-model:value="deptId" placeholder="请选择部门" clearable style="width: 200px"
              filterable label-field="name" value-field="value"  />
          </NFormItem>
          <NFormItem>
            <NButton ghost type="primary" style="width: 80rem" @click="queryTableData(true)">
              查询
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton ghost type="primary" style="width: 115rem" @click="handleImpport">
            工资单导入
          </NButton>
          <NButton ghost type="primary" style="width: 140rem" @click="handleSend"
            :disabled="dataListSelections?.length && chosenIdLength == demanIdLength ? false : true">
            下发工资单通知
          </NButton>
          <NButton type="error" style="width: 115px" @click="handleDelete" ghost
            :disabled="dataListSelections?.length && chosenIdLength == demanIdLength ? false : true">
            删除选中
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" :checked-row-keys="dataListSelections" @update:checked-row-keys="selectionChangeHandle" />
    </template>

    <template #pagination>
      <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize" :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againDelete" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
